<?php

/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace common\rest\actions\auth;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;
use common\rest\statics\ResponseDatum;
use common\rest\base\WxException;
use common\rest\statics\OperationResult;

/**
 * UpdateAction implements the API endpoint for updating a model.
 *
 * For more details and usage information on UpdateAction, see the [guide article on rest controllers](guide:rest-controllers).
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class UpdateAction extends Action {

    /**
     * @var string the scenario to be assigned to the model before it is validated and updated.
     */
    public $scenario = Model::SCENARIO_DEFAULT;

    /**
     * auth id
     * @var string 
     */
    public $authIdAttribute = "user_id";

    /**
     * Updates an existing model.
     * @param string $id the primary key of the model.
     * @return \yii\db\ActiveRecordInterface the model being updated
     * @throws ServerErrorHttpException if there is any error when updating the model
     */
    public function run($id) {
        try {
            $modelClass = $this->modelClass;
            $model = $modelClass::findOne([
                        'id' => $id,
                        $this->authIdAttribute => Yii::$app->user->id,
            ]);
            $params = Yii::$app->getRequest()->getBodyParams();

            if (is_null($model)) {
                throw new WxException(Yii::t('app.rest', 'Resource not found!'), OperationResult::ERROR_404, $params, null);
            }

            $model->load($params);
            if ($model->save()) {
                return ResponseDatum::getSuccessDatum(['msg' => Yii::t('app.c2', 'Operation completed successfully!')], $model);
            } elseif ($model->hasErrors()) {
                throw new WxException($model->getFirstErrorSummary(), OperationResult::ERROR_600, $params, ['errors' => $model->errors]);
            } else {
                throw new WxException(Yii::t('app.c2', 'Error: Operation can not finish!!'), OperationResult::ERROR_INTERNAL, $params, null);
            }
        } catch (WxException $ex) {
            return ResponseDatum::getErrorDatum([
                        'code' => $ex->getCode(),
                        'msg' => $ex->getMessage(),
                        'extraData' => $ex->extraData,
                            ], $ex->data);
        }
    }

}
